﻿using HAF.Dispatcher;
using HAF.Dispatcher.Enum;
using HAF.Dispatcher.Impl;
using HAF.Dispatcher.WorkItem;
using HAF.LogUtility.Assistantor;
using Iptv.MediaReporter.Entity;
using Iptv.MediaReporter.Enum;
using Iptv.MediaReporter.Helper;
using Iptv.MediaReporter.Model;
using Iptv.MediaReporter.SubItems;
using RDS.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Iptv.MediaReporter
{
    /// <summary>
    /// 媒资数据上报服务
    /// </summary>
    public class MediaReportItem : BaseWorkerItem, IPluginRegistable, IDisposable
    {
        const string _defLogName = "SysMonitor";
        private LoadConfig _runSiteConfig;
        string _dateRun = string.Empty;
        private List<ProgramEntity> _runProgramTasks = new List<ProgramEntity>();
        private List<MediaEntity> _runfingerTasks = new List<MediaEntity>();
        /// <summary>
        /// 任务自注册
        /// </summary>
        /// <param name="id"></param>
        /// <param name="objTask"></param>
        /// <returns></returns>
        public bool Regist(string id, object objTask)
        {
            if (string.IsNullOrEmpty(id))
            {
                WriteDebugMessage(string.Format("金沙引擎：方法{0}数据解析错误：{1}", System.Reflection.MethodBase.GetCurrentMethod().Name, "参数ID为空"));
                return false;
            }
            if (objTask == null)
            {
                WriteDebugMessage(string.Format("金沙引擎：方法{0}数据解析错误：{1}", System.Reflection.MethodBase.GetCurrentMethod().Name, "参数obj为空"));
                return false;
            }

            try
            {
                var downJob = new MediaReportItem()
                {
                    ID = int.Parse(TimeHelper.GetTimeStamp()),
                    TaskID = id,
                    Name = string.Concat("DownRes", id),
                    Priority = 10,
                    Model = EnumItemModel.Multi,
                    RedoTimes = 2,
                    WorkID = _defLogName,
                    WorkJson = JsonAssistant.Serialize(objTask),
                    AllowRemoteExec = false,
                    WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol,
                    WorkItems = objTask,
                    RunLogLevel = HAF.LogUtility.Enum.EnumLogLevel.All
                };
                Dispatcher.GetInstance().RegistTaskItem(downJob);

                //RuntimeControler.Tasks.Add(id, downJob);
                WriteDebugMessage(string.Format("金沙引擎：创建{0}工作项完成，下载资源请求已加入执行队列", id));
                return true;
            }
            catch (Exception ex)
            {
                WriteDebugMessage(string.Format("金沙引擎：方法{0}发生异常：{1}", System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString()));
                return false;
            }
        }

        /// <summary>
        /// 析构函数
        /// </summary>
        public void Dispose()
        {
            _runfingerTasks.Clear();
            _runfingerTasks = null;
            WriteDebugMessage("内容上报主线任务结束");
        }

        private void RefreshConfig()
        {
            //获取本地配置文件 每次执行的时候读取，实现热配置
            string loadConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RuntimeAdapter.PluginDir, "ReportConfig.json");
            ShowDebugMessage("获取本地配置文件{0}", loadConfigPath);
            _runSiteConfig = JsonAssistant.FromFile<LoadConfig>(loadConfigPath);
        }

        /// <summary>
        /// 
        /// </summary>
        public override void ExecItem()
        {
            base.ExecItem();
            //ReportMessageEvent = PushLog;
            RuntimeAdapter.Tasks.Clear();
            _runfingerTasks.Clear();
            _runProgramTasks.Clear();
            RuntimeAdapter.RunRepeat = false;

            RefreshConfig();
            //提取请求方输入参数
            Tack actTrace = JsonAssistant.Deserialize<Tack>(WorkJson);
            RuntimeAdapter.RunRepeat = actTrace.Action.ToLower().Equals("start");
            if (RuntimeAdapter.RunRepeat)
            {
                _dateRun = string.IsNullOrEmpty(actTrace.RunDate) ? DateTime.Now.ToString("yyyy-MM-dd") : actTrace.RunDate;
                ShowDebugMessage("上报任务循环模式启动！");
                Thread uploadMonitor = new Thread(delegate () { CreateTaskMonitor(); }) { Name = "TaskMonitor", IsBackground = true, Priority = ThreadPriority.Highest };
                uploadMonitor.Start();
            }
            else
            {
                ShowWarnMessage("上报任务循环模式将被停止");
                this.Statu = EnumRunItemStatu.End;
            }
        }

        #region Record Task
        private void CreateTaskMonitor()
        {
            //按天获取媒资元数据
            var tmpMedias = ReportDbHelper.GetInstance().GetProgramDatas(_dateRun);
            if (tmpMedias != null && tmpMedias.Count > 0)
            {
                ShowDebugMessage("本轮待上报任务数量为{0}个", tmpMedias.Count);
                //清理重复内容
                foreach (var item in tmpMedias)
                {
                    if (_runProgramTasks.Exists(t=>t.MediaID == item.MediaID))
                    {
                        continue;
                    }
                    _runProgramTasks.Add(item);
                }
            }
            if (_runProgramTasks.Count == 0)
            {
                return;
            }

            foreach (var item in _runProgramTasks)
            {
                //M3U8任务不执行
                ShowDebugMessageExt(item.MediaID, "添加任务[{0}]到前端展示", item.ProgramName);
                if (RuntimeAdapter.Tasks.Exists(t => t.ID == item.MediaID))
                {
                    UpdateTopTaskState(item.MediaID, 1);
                }
                else
                {
                    RuntimeAdapter.Tasks.Add(new RunTask()
                    {
                        ID = item.MediaID,
                        Type = "Report",
                        Comment = item.ProgramName,
                        CreateTime = DateTime.Now,
                        EndTime = DateTime.MaxValue,
                        Tag = item.MediaID,
                        Name = "内容建档",
                        State = 1
                    });
                }
                ShowDebugMessage("启动新的线程进行上报");
                //在当前线程中顺序执行run()方法中的代码，并不会启动新的线程
                //启动新的线程进行上报
                Thread thread = new Thread(delegate () { RunRecordTask(item); }) { Name = "", IsBackground = true };
                thread.Start();
                //Task.Run(delegate () { RunRecordTask(item, loadConfig); });
                //线程暂停30秒
                Thread.Sleep(30 * 1000);
            }

            RuntimeAdapter.RunRepeat = _runfingerTasks.Count > 0;

            ShowDebugMessage(string.Format("进入采集指纹循环模式！共{0}个任务需要执行", _runfingerTasks.Count));
            while (RuntimeAdapter.RunRepeat)
            {
                int iWaitTask = 0;
                try
                {
                    iWaitTask = _runfingerTasks.FindAll(t => t.State == EnumReportState.FingerPrintor).Count;
                    if (iWaitTask >= _runSiteConfig.MaxTaskCount)
                    {
                        ShowDebugMessage("指纹采集任务执行数量已达到最大值 {0}", _runSiteConfig.MaxTaskCount);
                        Thread.Sleep(1 * 60 * 1000); //暂停一分钟
                        RefreshConfig();
                        continue;
                    }

                    ShowDebugMessage("开始执行新的指纹采集上报任务");
                    //检查是否存在待执行的任务
                    if (_runfingerTasks.Exists(t => t.State == EnumReportState.Init))
                    {
                        var mediaTask = _runfingerTasks.Find(t => t.State == EnumReportState.Init);
                        //M3U8任务不执行
                        ShowDebugMessageExt(mediaTask.MediaID, "添加任务[{0}]到前端展示", mediaTask.MediaName);
                        if (RuntimeAdapter.Tasks.Exists(t => t.ID == mediaTask.MediaID))
                        {
                            UpdateTopTaskState(mediaTask.MediaID, 1);
                        }
                        else
                        {
                            RuntimeAdapter.Tasks.Add(new RunTask()
                            {
                                ID = mediaTask.MediaID,
                                Type = "Finger",
                                Comment = mediaTask.MediaName,
                                CreateTime = DateTime.Now,
                                EndTime = DateTime.MaxValue,
                                Tag = mediaTask.MediaID,
                                Name = "指纹采集",
                                State = 1
                            });
                        }
                        ShowDebugMessageExt(mediaTask.MediaID, "启动新的线程进行介质指纹采集");
                        //启动新的线程进行上报
                        Task.Run(delegate () { RunFingerTask(mediaTask); });
                    }
                }
                catch (Exception ex)
                {
                    ShowErrMessage(string.Format("方法{0}发生异常：{1}", System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString()));
                }

                Thread.Sleep(1 * 40 * 1000); //暂停 40秒
            }
            ShowDebugMessage("循环提取任务已失效");
        }

        /// <summary>
        /// 执行内容建档工作项
        /// </summary>
        /// <param name="program"></param>
        /// <param name="runConfig"></param>
        private void RunRecordTask(ProgramEntity program)
        {
            #region 入参校验
            if (program == null)
            {
                ShowErrMessage("入参校验失败");
                return;
            }
            #endregion 入参校验
            UpdateTopTaskState(program.MediaID, 2);
            ShowDebugMessageExt(program.MediaID, "建档任务{0}开始执行", program.MediaCode);
            using (MediaRecordItem recordItem = new MediaRecordItem())
            {
                recordItem.ID = int.Parse(TimeHelper.GetTimeStamp());
                recordItem.TaskID = Guid.NewGuid().ToString("N");
                recordItem.Name = string.Concat("Record", program.MediaID);
                recordItem.Priority = 10;
                recordItem.Model = EnumItemModel.Multi;
                recordItem.RedoTimes = 0;
                recordItem.WorkID = program.MediaID;
                recordItem.WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol;
                //WorkType = (int)SoapType.Host,
                recordItem.BeginTime = DateTime.Now.AddSeconds(40); //任务创建后40秒启动
                recordItem.WorkJson = string.Empty;
                recordItem.WorkItems = program;
                recordItem.Statu = EnumRunItemStatu.Begin;
                recordItem.CallBack = RecordTaskCallBack;
                recordItem.EndProcess = EndRecord;
                recordItem.ExecItem();
            }
        }

        private void RecordTaskCallBack(Object task, WorkOutMessage outMessage)
        {
            if (outMessage != null)
            {
                ShowDebugMessageExt(outMessage.ID, "回执指纹Hash为{0}", outMessage.Token);
            }
            
            if (outMessage != null && _runProgramTasks.Exists(t => t.MediaID == outMessage.ID))
            {
                var media = _runProgramTasks.Find(t => t.MediaID == outMessage.ID);
                if (media != null)
                {
                    media.TaskID = outMessage.Token;
                }
            }
            else
            {
                ShowDebugMessageExt(outMessage.ID, "未查找到任务{0}的数据", outMessage.ID);
            }
        }
        /// <summary>
        /// 建档完成
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="state"></param>
        private void EndRecord(string tid, bool state)
        {
            EndTopTask(tid, state ? 5 : -1);
            if (_runProgramTasks.Exists(t => t.MediaID == tid))
            {
                var tmpTask = _runProgramTasks.Find(t => t.MediaID == tid);
                //tmpTask.State = state ? EnumReportState.End : EnumReportState.Error;
                if (state)
                {
                    CreateFingerPrintTask(tid);
                }
            }
            else
            {
                ShowErrMessageExt(OutMessage.ID, "未找到指纹采集任务{0}", OutMessage.ID);
            }
        }
        #endregion Record Task

        #region 指纹采集任务
        private void ListMedia(string code, string taskId)
        {
            var tmpTasks = ReportDbHelper.GetInstance().GetMedia(code);
            if (tmpTasks != null && tmpTasks.Count > 0)
            {
                ShowDebugMessage("当然内容待采集介质任务数量为{0}个", tmpTasks.Count);
                //获取到的数据有重复数据（三端）
                foreach (var item in tmpTasks)
                {
                    if (_runfingerTasks.Exists(t => t.MediaID == item.MediaID))
                    {
                        continue;
                    }
                    item.TaskID = taskId;
                    _runfingerTasks.Add(item);
                }
            }
        }

        /// <summary>
        /// 创建指纹采集任务
        /// </summary>
        /// <param name="tid"></param>
        private void CreateFingerPrintTask(string tid)
        {
            //从内容集合中查找到内容数据
            var program = _runProgramTasks.Find(t => t.MediaID == tid);
            if (program != null)
            {
                //单集 直接获取介质数据
                if (program.MediaType == 0)
                {
                    ShowDebugMessageExt(program.MediaID, "当前任务{0}被判定为单集{1}，直接获取介质进行提交 {2}", program.ProgramName, program.MediaType, program.Counter);
                    ListMedia(program.MediaCode, program.TaskID);
                }
                else
                {
                    ShowDebugMessageExt(program.MediaID, "当前任务{0}被判定为多集{1}，开始获取所有子集数据 {2}", program.ProgramName, program.MediaType, program.Counter);
                    //多集 需要先获取所有子集数据，然后使用子集的编号去获取介质数据
                    var tmpSubPrograms = ReportDbHelper.GetInstance().GetSubProgramDatas(program.MediaCode);
                    if (tmpSubPrograms != null && tmpSubPrograms.Count > 0)
                    {
                        foreach (var item in tmpSubPrograms)
                        {
                            ListMedia(item.MediaCode, program.TaskID);
                        }
                    }
                    else
                    {
                        ShowDebugMessageExt(tid, "当前任务{0}未获取到子集任务，无法启动指纹采集工作");
                    }
                }
            }
        }

        private void RunFingerTask(MediaEntity media)
        {
            if (media == null || string.IsNullOrEmpty(media.TaskID) || string.IsNullOrEmpty(media.RemoteFullPath))
            {
                ShowErrMessageExt(media.MediaID, "创建指纹采集任务入参校验失败");
                media.State = EnumReportState.Error;
                UpdateTopTaskState(media.MediaID, -1);
                return;
            }
            ShowDebugMessageExt(media.MediaID, "{0}", JsonAssistant.Serialize(media));
            //ftp://unicom:UD_unicom2024@172.25.8.180:21/202412/23/c20a984cbb5bc000_OTT_HD_1920X1080_4000_VBR.mp4

            UpdateTopTaskState(media.MediaID, 2);
            media.State = EnumReportState.FingerPrintor;
            ShowDebugMessageExt(media.MediaID, "指纹采集任务{0}开始执行", media.MediaCode);

            using (MediaFingerItem fingerItem = new MediaFingerItem())
            {
                fingerItem.ID = int.Parse(TimeHelper.GetTimeStamp());
                fingerItem.TaskID = Guid.NewGuid().ToString("N");
                fingerItem.Name = string.Concat("Record", media.TaskID);
                fingerItem.Priority = 10;
                fingerItem.Model = EnumItemModel.Multi;
                fingerItem.RedoTimes = 0;
                fingerItem.WorkID = media.MediaID;
                fingerItem.WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol;
                //WorkType = (int)SoapType.Host,
                fingerItem.BeginTime = DateTime.Now.AddSeconds(40); //任务创建后40秒启动
                fingerItem.WorkJson = string.Empty;
                fingerItem.WorkItems = media;
                fingerItem.Statu = EnumRunItemStatu.Begin;
                fingerItem.CallBack = FingerCallBack;
                fingerItem.EndProcess = EndFingerTaskState;
                fingerItem.ExecItem();
            }
        }

        private void FingerCallBack(object task, WorkOutMessage outMessage)
        {
            if (outMessage != null)
            {
                if (_runfingerTasks.Exists(t => t.MediaID == outMessage.ID))
                {
                    //指纹采集输出的Token值
                    ShowDebugMessageExt(OutMessage.ID, "指纹采集回执Hasn值为{0}", OutMessage.Token);
                    _runfingerTasks.Find(t => t.MediaID == outMessage.ID).Token = outMessage.Token;
                    _runfingerTasks.Find(t => t.MediaID == outMessage.ID).JobID = outMessage.CmdUrl;
                }
                else
                {
                    ShowErrMessageExt(OutMessage.ID, "未找到指纹采集任务{0}", OutMessage.ID);
                }
                
                string aa = outMessage.Token;
            }
        }

        private void EndFingerTaskState(string tid, bool state)
        {
            EndTopTask(tid, state ? 5 : -1);
            if (_runfingerTasks.Exists(t=> t.MediaID == tid))
            {
                var tmpTask = _runfingerTasks.Find(t => t.MediaID == tid);
                tmpTask.State = state ? EnumReportState.End : EnumReportState.Error;
                if (state)
                {
                    CreateFingerReportItem(tmpTask);
                }
            }
            else
            {
                ShowErrMessageExt(OutMessage.ID, "未找到指纹上报任务{0}", OutMessage.ID);
            }
        }

        #endregion 指纹采集任务

        #region 指纹上报任务
        private void CreateFingerReportItem(MediaEntity media)
        {
            //使用jobId作为任务编号
            ShowDebugMessageExt(media.MediaID, "添加指纹上报任务[{0}]到前端展示", media.MediaName);
            if (RuntimeAdapter.Tasks.Exists(t => t.ID == media.JobID))
            {
                UpdateTopTaskState(media.JobID, 1);
            }
            else
            {
                RuntimeAdapter.Tasks.Add(new RunTask()
                {
                    ID = media.JobID,
                    Type = "FingerReport",
                    Comment = media.MediaName,
                    CreateTime = DateTime.Now,
                    EndTime = DateTime.MaxValue,
                    Tag = media.MediaID,
                    Name = "指纹上报",
                    State = 1
                });
            }
            ShowDebugMessageExt(media.MediaID, "启动新的线程执行指纹上报工作");
            //启动新的线程进行上报
            Thread thread = new Thread(delegate ()
            {
                using (FingerReportItem reportItem = new FingerReportItem())
                {
                    reportItem.ID = int.Parse(TimeHelper.GetTimeStamp());
                    reportItem.TaskID = Guid.NewGuid().ToString("N");
                    reportItem.Name = string.Concat("FingerReport", media.MediaID);
                    reportItem.Priority = 10;
                    reportItem.Model = EnumItemModel.Multi;
                    reportItem.RedoTimes = 0;
                    reportItem.WorkID = media.MediaID;
                    reportItem.WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol;
                    //WorkType = (int)SoapType.Host,
                    reportItem.BeginTime = DateTime.Now.AddSeconds(40); //任务创建后40秒启动
                    reportItem.WorkJson = string.Empty;
                    reportItem.WorkItems = media;
                    reportItem.Statu = EnumRunItemStatu.Begin;
                    //reportItem.CallBack = FingerCallBack;
                    reportItem.EndProcess = EndFingerReportState;
                    reportItem.ExecItem();
                }
            })
            { Name = "FingerReport", IsBackground = true };
            thread.Start();

            UpdateTopTaskState(media.JobID, 2);
        }

        private void EndFingerReportState(string tid, bool state)
        {
            EndTopTask(tid, state ? 5 : -1);
            if (_runfingerTasks.Exists(t => t.JobID == tid))
            {
                var tmpTask = _runfingerTasks.Find(t => t.JobID == tid);
                tmpTask.State = state ? EnumReportState.End : EnumReportState.Error;
                if (state)
                {
                    CreatePublishReportItem(tmpTask);
                }
            }
            else
            {
                ShowErrMessageExt(OutMessage.ID, "未找到发布任务{0}", OutMessage.ID);
            }
        }
        #endregion 指纹上报任务

        #region 发布上报任务
        private void CreatePublishReportItem(MediaEntity media)
        {
            //使用jobId作为任务编号
            ShowDebugMessageExt(media.MediaID, "添加发布上报任务[{0}]到前端展示", media.MediaName);
            media.JobID = Guid.NewGuid().ToString("N");
            //添加到前端展示
            RuntimeAdapter.Tasks.Add(new RunTask()
            {
                ID = media.JobID,
                Type = "PublishReport",
                Comment = media.MediaName,
                CreateTime = DateTime.Now,
                EndTime = DateTime.MaxValue,
                Tag = media.MediaID,
                Name = "发布上报",
                State = 1
            });
            ShowDebugMessageExt(media.MediaID, "启动新的线程执行发布上报工作");
            //启动新的线程进行上报
            Thread thread = new Thread(delegate ()
            {
                using (FingerReportItem reportItem = new FingerReportItem())
                {
                    reportItem.ID = int.Parse(TimeHelper.GetTimeStamp());
                    reportItem.TaskID = Guid.NewGuid().ToString("N");
                    reportItem.Name = string.Concat("PublishReport", media.MediaID);
                    reportItem.Priority = 10;
                    reportItem.Model = EnumItemModel.Multi;
                    reportItem.RedoTimes = 0;
                    reportItem.WorkID = media.MediaID;
                    reportItem.WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol;
                    //WorkType = (int)SoapType.Host,
                    reportItem.BeginTime = DateTime.Now.AddSeconds(40); //任务创建后40秒启动
                    reportItem.WorkJson = string.Empty;
                    reportItem.WorkItems = media;
                    reportItem.Statu = EnumRunItemStatu.Begin;
                    //reportItem.CallBack = FingerCallBack;
                    reportItem.EndProcess = EndPublishReportState;
                    reportItem.ExecItem();
                }
            })
            { Name = "PublishReport", IsBackground = true };
            thread.Start();

            UpdateTopTaskState(media.JobID, 2);
        }

        private void EndPublishReportState(string tid, bool state)
        {
            EndTopTask(tid, state ? 5 : -1);
            if (_runfingerTasks.Exists(t => t.JobID == tid))
            {
                var tmpTask = _runfingerTasks.Find(t => t.JobID == tid);
                tmpTask.State = state ? EnumReportState.End : EnumReportState.Error;
                if (state)
                {
                    CreateDetailReportItem(tmpTask);
                }
            }
            else
            {
                ShowErrMessageExt(OutMessage.ID, "未找到明细上报任务{0}", OutMessage.ID);
            }
        }

        #endregion 发布上报任务

        #region 明细上报任务
        private void CreateDetailReportItem(MediaEntity media)
        {
            //使用jobId作为任务编号
            ShowDebugMessageExt(media.MediaID, "添加明细上报任务[{0}]到前端展示", media.MediaName);
            media.JobID = Guid.NewGuid().ToString("N");
            //添加到前端展示
            RuntimeAdapter.Tasks.Add(new RunTask()
            {
                ID = media.JobID,
                Type = "DetailReport",
                Comment = media.MediaName,
                CreateTime = DateTime.Now,
                EndTime = DateTime.MaxValue,
                Tag = media.MediaID,
                Name = "明细上报",
                State = 1
            });
            ShowDebugMessageExt(media.MediaID, "启动新的线程执行明细上报工作");
            //启动新的线程进行上报
            Thread thread = new Thread(delegate ()
            {
                using (DetailReportItem reportItem = new DetailReportItem())
                {
                    reportItem.ID = int.Parse(TimeHelper.GetTimeStamp());
                    reportItem.TaskID = Guid.NewGuid().ToString("N");
                    reportItem.Name = string.Concat("DetailReport", media.MediaID);
                    reportItem.Priority = 10;
                    reportItem.Model = EnumItemModel.Multi;
                    reportItem.RedoTimes = 0;
                    reportItem.WorkID = media.MediaID;
                    reportItem.WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol;
                    //WorkType = (int)SoapType.Host,
                    reportItem.BeginTime = DateTime.Now.AddSeconds(40); //任务创建后40秒启动
                    reportItem.WorkJson = string.Empty;
                    reportItem.WorkItems = media;
                    reportItem.Statu = EnumRunItemStatu.Begin;
                    //reportItem.CallBack = FingerCallBack;
                    reportItem.EndProcess = EndDetailReportState;
                    reportItem.ExecItem();
                }
            })
            { Name = "DetailReport", IsBackground = true };
            thread.Start();

            UpdateTopTaskState(media.JobID, 2);
        }

        private void EndDetailReportState(string tid, bool state)
        {
            EndTopTask(tid, state ? 5 : -1);
            if (_runfingerTasks.Exists(t => t.JobID == tid))
            {
                var tmpTask = _runfingerTasks.Find(t => t.JobID == tid);
                tmpTask.State = state ? EnumReportState.End : EnumReportState.Error;
                if (state)
                {
                    CreateAuditReportItem(tmpTask);
                }
            }
            else
            {
                ShowErrMessageExt(OutMessage.ID, "未找到内容审核上报任务{0}", OutMessage.ID);
            }
        }

        #endregion 明细上报任务

        #region 审核上报任务
        private void CreateAuditReportItem(MediaEntity media)
        {
            //使用jobId作为任务编号
            ShowDebugMessageExt(media.MediaID, "添加审核上报任务[{0}]到前端展示", media.MediaName);
            media.JobID = Guid.NewGuid().ToString("N");
            //添加到前端展示
            RuntimeAdapter.Tasks.Add(new RunTask()
            {
                ID = media.JobID,
                Type = "AuditReport",
                Comment = media.MediaName,
                CreateTime = DateTime.Now,
                EndTime = DateTime.MaxValue,
                Tag = media.MediaID,
                Name = "审核上报",
                State = 1
            });
            ShowDebugMessageExt(media.MediaID, "启动新的线程执行审核上报工作");
            //启动新的线程进行上报
            Thread thread = new Thread(delegate ()
            {
                using (AuditReportItem reportItem = new AuditReportItem())
                {
                    reportItem.ID = int.Parse(TimeHelper.GetTimeStamp());
                    reportItem.TaskID = Guid.NewGuid().ToString("N");
                    reportItem.Name = string.Concat("AuditReport", media.MediaID);
                    reportItem.Priority = 10;
                    reportItem.Model = EnumItemModel.Multi;
                    reportItem.RedoTimes = 0;
                    reportItem.WorkID = media.MediaID;
                    reportItem.WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol;
                    //WorkType = (int)SoapType.Host,
                    reportItem.BeginTime = DateTime.Now.AddSeconds(40); //任务创建后40秒启动
                    reportItem.WorkJson = string.Empty;
                    reportItem.WorkItems = media;
                    reportItem.Statu = EnumRunItemStatu.Begin;
                    //reportItem.CallBack = FingerCallBack;
                    reportItem.EndProcess = EndAuditReportState;
                    reportItem.ExecItem();
                }
            })
            { Name = "AuditReport", IsBackground = true };
            thread.Start();

            UpdateTopTaskState(media.JobID, 2);
        }

        private void EndAuditReportState(string tid, bool state)
        {
            EndTopTask(tid, state ? 5 : -1);
            if (_runfingerTasks.Exists(t => t.JobID == tid))
            {
                var tmpTask = _runfingerTasks.Find(t => t.JobID == tid);
                tmpTask.State = state ? EnumReportState.End : EnumReportState.Error;
                if (state)
                {
                    CreatePictureReportItem(tmpTask);
                }
            }
            else
            {
                ShowErrMessageExt(OutMessage.ID, "未找到海报任务{0}", OutMessage.ID);
            }
        }

        #endregion 审核上报任务

        #region 图片上报任务
        private void CreatePictureReportItem(MediaEntity media)
        {
            //使用jobId作为任务编号
            ShowDebugMessageExt(media.MediaID, "添加图片上报任务[{0}]到前端展示", media.MediaName);
            media.JobID = Guid.NewGuid().ToString("N");
            //添加到前端展示
            RuntimeAdapter.Tasks.Add(new RunTask()
            {
                ID = media.JobID,
                Type = "PictureReport",
                Comment = media.MediaName,
                CreateTime = DateTime.Now,
                EndTime = DateTime.MaxValue,
                Tag = media.MediaID,
                Name = "图片上报",
                State = 1
            });
            ShowDebugMessageExt(media.MediaID, "启动新的线程执行图片上报工作");
            //启动新的线程进行上报
            Thread thread = new Thread(delegate ()
            {
                using (var reportItem = new PictureReportItem())
                {
                    reportItem.ID = int.Parse(TimeHelper.GetTimeStamp());
                    reportItem.TaskID = Guid.NewGuid().ToString("N");
                    reportItem.Name = string.Concat("PictureReport", media.MediaID);
                    reportItem.Priority = 10;
                    reportItem.Model = EnumItemModel.Multi;
                    reportItem.RedoTimes = 0;
                    reportItem.WorkID = media.MediaID;
                    reportItem.WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol;
                    //WorkType = (int)SoapType.Host,
                    reportItem.BeginTime = DateTime.Now.AddSeconds(40); //任务创建后40秒启动
                    reportItem.WorkJson = string.Empty;
                    reportItem.WorkItems = media;
                    reportItem.Statu = EnumRunItemStatu.Begin;
                    //reportItem.CallBack = FingerCallBack;
                    reportItem.EndProcess = EndPictureReportState;
                    reportItem.ExecItem();
                }
            })
            { Name = "PictureReport", IsBackground = true };
            thread.Start();

            UpdateTopTaskState(media.JobID, 2);
        }

        private void EndPictureReportState(string tid, bool state)
        {
            EndTopTask(tid, state ? 5 : -1);
            if (_runfingerTasks.Exists(t => t.JobID == tid))
            {
                var tmpTask = _runfingerTasks.Find(t => t.JobID == tid);
                tmpTask.State = state ? EnumReportState.End : EnumReportState.Error;
                if (state)
                {
                    //CreateFingerReportItem(tmpTask);
                }
            }
            else
            {
                ShowErrMessageExt(OutMessage.ID, "未找到海报任务{0}", OutMessage.ID);
            }
        }

        #endregion 图片上报任务

        #region 前端任务处理
        /// <summary>
        /// 更新前端任务列表基础数据
        /// </summary>
        /// <param name="correlateId"></param>
        /// <param name="tag"></param>
        /// <param name="siteName"></param>
        private void UpdateTopTaskInfo(string correlateId, string tag, string siteName)
        {
            try
            {
                //通过任务编号找到缓存中执行的任务数据
                var runTaskItem = RuntimeAdapter.Tasks.Find(t => t.ID == correlateId);
                if (runTaskItem != null)
                {
                    runTaskItem.Comment = correlateId; // itemCfg.FileSets[0].Group;
                    runTaskItem.Tag = tag; // itemCfg.Tag;
                    runTaskItem.Name = siteName; // itemCfg.Site;
                }
            }
            catch (Exception ex)
            {
                ShowDebugMessage(ex.ToString());
            }

        }

        private void UpdateTopTaskName(string correlateId, string siteName)
        {
            try
            {
                //通过任务编号找到缓存中执行的任务数据
                var runTaskItem = RuntimeAdapter.Tasks.Find(t => t.ID == correlateId);
                if (runTaskItem != null)
                {
                    runTaskItem.Comment = string.Concat(runTaskItem.Comment, "[", siteName, "]"); // itemCfg.FileSets[0].Group;
                }
            }
            catch (Exception ex)
            {
                ShowDebugMessage(ex.ToString());
            }

        }

        /// <summary>
        /// 更新前端任务状态
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="value"></param>
        private void UpdateTopTaskState(string tid, int value)
        {
            try
            {
                if (RuntimeAdapter.Tasks.Exists(t => t.ID == tid))
                {
                    var runTaskItem = RuntimeAdapter.Tasks.Find(t => t.ID == tid);
                    runTaskItem.State = value;
                }
                else
                {
                    ShowDebugMessageExt(tid, "未找到编号为{0}的任务", tid);
                }
            }
            catch (Exception ex)
            {
                ShowDebugMessage(ex.ToString());
            }

            //RuntimeAdapter.Tasks.Find(t => t.ID == TaskID).State = value;
        }
        /// <summary>
        /// 结束任务
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="value"></param>
        private void EndTopTask(string tid, int value)
        {
            //两种方式写前台监控队列的值
            RuntimeAdapter.Tasks.ForEach(delegate (RunTask t) { if (t.ID == tid) { t.State = value; t.EndTime = DateTime.Now; } });
            //RuntimeAdapter.Tasks.Find(t => t.ID == TaskID).State = responseMsg.Code;
            //RuntimeAdapter.Tasks.Find(t => t.ID == TaskID).EndTime = DateTime.Now;
        }
        #endregion 前端任务处理
    }
}
